package cn.lger.service;

import cn.lger.dao.UserDao;
import cn.lger.encoder.PasswordEncoder;
import cn.lger.pojo.User;
import cn.lger.util.StringEmptyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Code that Changed the World
 *
 * @author Pro
 * @date 2018-06-14.
 */

@Service
public class UserService {

    @Resource
    private UserDao userDao;
    @Resource
    private PasswordEncoder encoder;

    public User findOneByUsernameAndPassword(String username, String password) {
        User user = userDao.findOneByUsername(username);
        if (encoder.matches(password, user.getPassword())) {
            return user;
        } else {
            return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public int insertOne(User user) {
        String code = encoder.encoder(user.getPassword());
        user.setPassword(code);
        return userDao.insertOne(user);
    }

    @Transactional(rollbackFor = Exception.class)
    public int update(User user) {

        boolean isModify = false;

        if (StringEmptyUtil.notEmpty(user.getPassword())) {
            isModify = true;
            user.setPassword(encoder.encoder(user.getPassword()));
        }

        if (StringEmptyUtil.notEmpty(user.getEmail())){
            isModify = true;
        }

        if (isModify) {
            return userDao.updateOne(user);
        } else {
            return 0;
        }

    }

    public int checkUsername(String username) {
        return userDao.checkUsername(username);
    }
}
